package merchantService

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/spf13/cast"
	"hc_server/pkg/channel"
	pkgFile "hc_server/pkg/file"
	"hc_server/pkg/setting"
	"hc_server/pkg/util"
	"hc_server/routers/models"
)

type Merchant struct {
	Id         int //表id
	UserId     int //当前登录人id
	MerchantId int //商户id

	//商户基本信息
	MerchantMobile     string //商户手机号
	MerchantType       int    //商户类型 1=小微商户 2=个体商户 3=企业商户
	MerchantShopTypeId int    //店铺类型 id
	AgentId            int    //代理商id
	SalesmenId         int    //业务员id

	//商户门店信息
	MerchantRangeCode         int     //LianMcc表code 经营范围code
	MerchantName              string  //商户名称
	MerchantLongitude         float64 //经度
	MerchantLatitude          float64 //纬度
	MerchantAddress           string  //商户地址
	MerchantAddressId         int     //LianCode表id 省市区
	MerchantPostcode          string  //邮编
	MerchantFrontPhoto        string  //商户门脸照片
	MerchantCheckstandPhoto   string  //商户收银台照片
	MerchantIndoorPhoto       string  //经营场所照片
	MerchantRelationCertPhoto string  //总-门店关系说明函 merchant_shop_types = 3时必填

	LicensePhoto     string //执照照片名称
	LicenseName      string //营业执照名称
	LicenseCode      string //执照注册号
	LicenseBeginTime string //执照注册开始时间
	LicenseEndTime   string //执照注册结束时间
	LicenseAddress   string //执照地址

	//法人信息
	LegalPersonName                string //法人姓名
	LegalPersonIdcard              string //法人身份证
	LegalPersonIdcardPhotoFront    string //法人身份证照片正面
	LegalPersonIdcardPhotoBack     string //法人身份证照片反面
	LegalPersonIdcardHold          string //手持身份证
	LegalPersonIdcardValidityBegin string //法人身份证有效期始
	LegalPersonIdcardValidityEnd   string //法人身份证有效期至
	LegalContactType               int    //商户联系人类型 0-法人；1-委托人 ，小微，只能是0-法人
	LegalContactName               string //联系人姓名
	LegalContactIdCardNo           string //联系人身份证号
	LegalContactMobile             string //联系人手机号

	//结算信息
	BankCardholderName     string //持卡人姓名
	SettleBankcardNo       string //银行卡号
	SettleBankMobile       string //银行预留手机号
	SettleName             string //结算户名 法人对私结算：与法人姓名一致； 非法人对私结算：与非法人身份证信息一致； 法人对公结算：与营业执照注册名称一致
	BankCode               string //开户省市
	SettleBankcardFrontPic string //银行卡照片
	BankName               string //开户银行名称
	BankCity               string //银行所在城市
	SettleSubbranchCode    string //开户支行联行号
	SettleAccountType      int    //结算账户类型：1-法人对私；2-非法人对私；3-法人对公；merchantType=1-小微，该参数必须为1-法人对私
	SettleIdcardNo         string //结算人身份证号（非法人对私必填）
	SettleIdcardStartDate  string //结算人身份证有效期起始日期（非法人对私必填） 格式：yyyy-MM-dd
	SettleIdcardEndDate    string //结算人身份证有效期结束日期（非法人对私必填） 格式：yyyy-MM-dd
	SettleIdcardFrontName  string //结算人身份证正面照(图片id)（非法人对私必填）
	SettleIdcardBackName   string //结算人身份证反面照(图片id)（非法人对私必填）
	SettleAuthName         string //结算授权书图片(图片id)（非法人对私必填）

	LDAuditType int //审核类型：1-进件审核（入驻+修改）；2-结算信息变更审核

	PageNum  int
	PageSize int
	Keyword  string
	Type     int //0=直属商户 1=下级商户

	//查询
	Info       *string //商户名称/商户编号
	MerType    *int    //商户类型 1=小微商户 2=个体商户 3=企业商户
	Name       *string //商户全称
	ShopType   *int    //店铺类型 0=全部 1=总店 2=分店 4分账接收方
	AuditType  *int    //审核状态 0=全部 1=审核通过 2=审核中 3=驳回
	WechatType *int    //微信认证状态 0=全部 1=未认证 2=已认证
	AliType    *int    //支付宝认证状态 0=全部 1=未认证 2=已认证
	SubmitTime *string //提交时间 YYYY-MM-DD hh:mm:ss
	AuditTime  *string //审核时间 YYYY-MM-DD hh:mm:ss
	ActivityId *int    //活动id
	SaleId     *int    //业务员id

}

// MerchantGetInfoByID 通过id获取详情
//func (m *Merchant) MerchantGetInfoByID() (map[string]string, error) {
//	return models.MerchantGetInfoByID(m.Id)
//}

// MerchantTempInfoAdd 添加临时商户信息
func (m *Merchant) MerchantTempInfoAdd() (map[string]string, error) {
	if (m.MerchantShopTypeId == 2 || m.MerchantShopTypeId == 3) && m.MerchantId == 0 {
		return nil, errors.New("请绑定主店信息")
	}
	//判断临时表中是否有此商户
	exist, _ := models.MerchantExistByMobile(m.MerchantMobile)
	if exist {
		return nil, errors.New("该手机号已存在")
	}

	//判断是否添加了主店，如果添加判断主店逻辑
	if m.MerchantShopTypeId == 2 || m.MerchantShopTypeId == 3 {
		info, err := models.MerchantByID(m.MerchantId)
		if err != nil {
			return nil, err
		}

		if cast.ToInt(info.MerchantTypeID) == 1 && (m.MerchantType == 2 || m.MerchantType == 3) {
			return nil, errors.New("总店是小微，分店只能是小微")
		}

		if cast.ToInt(info.MerchantTypeID) == 2 && m.MerchantType == 3 {
			return nil, errors.New("总店是个体，分店可以是小微、个体")
		}
	}

	if m.SalesmenId > 0 {
		//判断业务员是否存在
		err := models.SalesmenExistByID(m.SalesmenId)
		if err != nil {
			return nil, err
		}
	}

	if m.AgentId > 0 {
		//判断代理商是否存在
		_, err := models.AgentExistByID(m.AgentId)
		if err != nil {
			return nil, err
		}
	}

	return models.MerchantTempInfoAdd(m.MerchantMobile, m.MerchantType, m.MerchantShopTypeId, m.AgentId, m.SalesmenId, m.MerchantId)
}

// MerchantTempShopAdd 添加商户门店信息
func (m *Merchant) MerchantTempShopAdd() error {
	if util.ContainsSpecialChars(m.MerchantName) {
		return errors.New("商户门店名称不能包含特殊字符")
	}
	mer, err := models.MerchantTempInfoById(m.Id)
	if err != nil {
		return err
	}
	if mer.MerchantShopTypeID == 3 && len(m.MerchantRelationCertPhoto) == 0 {
		return errors.New("总分店同个营业执照，必须上传总-门店关系说明函")
	}
	return models.MerchantTempShopAdd(m.Id, m.MerchantName, m.MerchantAddress, cast.ToString(m.MerchantAddressId), m.MerchantFrontPhoto, m.MerchantCheckstandPhoto, m.MerchantIndoorPhoto, m.MerchantRelationCertPhoto, m.MerchantRangeCode, m.MerchantLongitude, m.MerchantLatitude)
}

// MerchantTempLegalAdd 添加商户法人信息
func (m *Merchant) MerchantTempLegalAdd() error {
	mer, err := models.MerchantTempInfoById(m.Id)
	if err != nil {
		return err
	}
	if mer.MerchantTypeID == 1 && m.LegalContactType != 0 {
		return errors.New("小微只能是法人")
	}
	if (mer.MerchantTypeID == 2 || mer.MerchantTypeID == 3) && len(m.LegalContactName) == 0 {
		return errors.New("请输入联系人姓名")
	}
	if (mer.MerchantTypeID == 2 || mer.MerchantTypeID == 3) && len(m.LegalContactIdCardNo) == 0 {
		return errors.New("请输入联系人身份证号")
	}
	return models.MerchantTempLegalAdd(m.LegalPersonName, m.LegalPersonIdcard, m.LegalPersonIdcardPhotoFront, m.LegalPersonIdcardPhotoBack, m.LegalPersonIdcardHold, m.LegalContactIdCardNo, m.LegalContactName, m.LegalContactMobile, m.Id, m.LegalContactType, m.LegalPersonIdcardValidityBegin, m.LegalPersonIdcardValidityEnd)
}

// MerchantTempMerchantLicenseInfoAdd 添加商户执照信息
func (m *Merchant) MerchantTempMerchantLicenseInfoAdd() error {
	return models.MerchantTempMerchantLicenseInfoAdd(m.LicensePhoto, m.LicenseName, m.LicenseCode, m.LicenseBeginTime, m.LicenseEndTime, m.LicenseAddress, m.ActivityId, m.Id)
}

// MerchantTempSettleAdd 添加商户银行卡信息
func (m *Merchant) MerchantTempSettleAdd() error {
	//临时表中取出用户全部信息
	merchant, err := models.MerchantTempInfoById(m.Id)
	if err != nil {
		return err
	}

	_, err = models.MerchantExistByMobile(merchant.MerchantMobile)
	if err == nil {
		return errors.New("此手机号码已存在")
	}

	//merchantType=2-个体，3-企业，商户信息
	if merchant.MerchantTypeID == 2 || merchant.MerchantTypeID == 3 {
		if len(merchant.LicensePhoto) == 0 || len(merchant.LicenseName) == 0 || len(merchant.LicenseCode) == 0 || len(merchant.LicenseStartDate) == 0 || len(merchant.LicenseEndDate) == 0 || len(merchant.LicenseAddress) == 0 {
			return errors.New("请填写商户信息")
		}
	}

	if merchant.MerchantShopTypeID == 1 && m.SettleAccountType != 1 {
		return errors.New("小微企业，只能选择法人对私")
	}

	if m.SettleAccountType == 2 && len(m.SettleName) == 0 {
		return errors.New("请输入结算户名")
	}

	var settleName string
	if m.SettleAccountType == 1 {
		//法人对私结算：与法人姓名一致；
		settleName = merchant.LegalPersonName
	} else if m.SettleAccountType == 2 {
		//非法人对私结算：与非法人身份证信息一致；
		settleName = m.SettleName
	} else {
		//法人对公结算：与营业执照注册名称一致
		settleName = merchant.LicenseName
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardFrontName) == 0 {
		return errors.New("身份证正面照不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardBackName) == 0 {
		return errors.New("身份证背面照不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleAuthName) == 0 {
		return errors.New("结算授权书图片不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardNo) == 0 {
		return errors.New("结算人身份证号不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardStartDate) == 0 {
		return errors.New("结算人身份证有效期起始日期不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardEndDate) == 0 {
		return errors.New("结算人身份证有效期结束日期不能为空")
	}

	//临时表中添加结算信息
	mapd, err := models.MerchantTempBankAdd(m.Id, m.SettleAccountType, m.SettleBankcardFrontPic, m.SettleBankcardNo, m.SettleBankMobile, m.SettleSubbranchCode, m.SettleIdcardNo,
		m.SettleIdcardStartDate, m.SettleIdcardEndDate, m.SettleIdcardFrontName, m.SettleIdcardBackName, m.SettleAuthName, settleName)
	if err != nil {
		return err
	}

	//把用户的所有图片移出临时文件夹
	err = pkgFile.MoveDirTempToUser(setting.GetConfig().App.MerchantPath + cast.ToString(m.Id))
	if err != nil {
		return err
	}

	//删除临时文件夹
	err = pkgFile.RemoveDir(setting.GetConfig().App.MerchantPath + cast.ToString(m.Id))
	if err != nil {
		return err
	}

	no := fmt.Sprintf("%06d", cast.ToInt(models.MerchantGetMaxMerchantNo())+1)
	merchant.MerchantNo = no

	//添加商户信息表
	newMer, err := models.MerchantInfoAdd(merchant)
	if err != nil {
		return err
	}

	//代理关系表
	agentRelation, err := models.AgentRelationGetInfoByAgentNo(merchant.AgentID)
	if err != nil {
		return err
	}

	//添加代理关系表
	err = models.MerchantRelationAdd(newMer.ID, merchant.AgentID, agentRelation["relation"])
	if err != nil {
		return err
	}

	err = models.LianMerchantUpdate(cast.ToString(mapd["id"]), map[string]interface{}{"merchant_id": newMer.ID})
	if err != nil {
		return err
	}

	//删除临时表
	err = models.MerchantTempDeleteById(mapd["id"])
	if err != nil {
		return err
	}

	//请求联动商户入驻接口
	data, err := channelToLian(newMer)
	if err != nil {
		//更新审核状态
		err = models.MerchantInfoUpdate(map[string]interface{}{"audit_status": 3}, newMer.ID)
		if err != nil {
			return err
		}
		return err
	}

	//更新审核状态
	err = models.MerchantInfoUpdate(map[string]interface{}{"audit_status": 2, "ld_business_id": data["businessId"], "ld_merchant_id": data["merchantId"]}, newMer.ID)
	if err != nil {
		return err
	}

	return nil
}

// MerchantGetMerchantList 获取商户列表
func (m *Merchant) MerchantGetMerchantList() map[string]interface{} {
	return models.MerchantGetMerchantList(m.UserId, m.Type, m.PageNum, m.PageSize)
}

// MerchantManagerSearch 商户管理查询
func (m *Merchant) MerchantManagerSearch() map[string]interface{} {
	conditions := "1=1"

	if m.Info != nil && *m.Info != "" {
		//conditions = fmt.Sprintf("%s AND (merchants.merchant_name LIKE '%s' OR merchants.merchant_no LIKE '%s')", conditions, "%"+*m.Info+"%", "%"+*m.Info+"%")
	}
	if m.MerType != nil && *m.MerType != 0 {
		conditions = fmt.Sprintf("%s AND merchants.merchant_type_id = %d", conditions, *m.MerType)
	}
	if m.Name != nil && *m.Name != "" {
		conditions = fmt.Sprintf("%s AND merchants.merchant_name = '%s'", conditions, cast.ToString(*m.Name))
	}
	if m.ShopType != nil && *m.ShopType != 0 {
		conditions = fmt.Sprintf("%s AND merchants.merchant_shop_type_id = %d", conditions, *m.ShopType)
	}
	if m.AuditType != nil && *m.AuditType != 0 {
		conditions = fmt.Sprintf("%s AND merchants.audit_status = %d", conditions, *m.AuditType)
	}
	if m.WechatType != nil && *m.WechatType != 0 {
		conditions = fmt.Sprintf("%s AND merchants.wechat_status = %d", conditions, *m.WechatType)
	}
	if m.SubmitTime != nil && *m.SubmitTime != "" {
		conditions = fmt.Sprintf("%s AND merchants.created_at = '%s'", conditions, *m.SubmitTime)
	}
	if m.AuditTime != nil && *m.AuditTime != "" {
		conditions = fmt.Sprintf("%s AND merchants.audit_time = '%s'", conditions, *m.AuditTime)
	}
	if m.ActivityId != nil && *m.ActivityId != 0 {
		conditions = fmt.Sprintf("%s AND merchants.activity_id = %d", conditions, *m.ActivityId)
	}
	if m.SaleId != nil && *m.SaleId != 0 {
		conditions = fmt.Sprintf("%s AND merchants.salesmen_id = %d", conditions, *m.SaleId)
	}

	return models.MerchantManagerSearch(conditions, m.AgentId, m.Type, m.PageNum, m.PageSize)
}

// MerchantManagerInfo 商户管理详情
func (m *Merchant) MerchantManagerInfo() (map[string]interface{}, error) {
	info, err := models.MerchantGetMerchantInfo(m.MerchantId)
	if err != nil {
		return nil, err
	}

	devices, err := models.DeviceList(m.MerchantId)
	if err != nil {
		return nil, err
	}

	rate, err := models.MerchantRateInfoByMerchantId(m.MerchantId)
	if err != nil {
		return nil, err
	}

	settlementRate, err := models.MerchantSettlementRateInfoByMerchantId(m.MerchantId)
	if err != nil {
		return nil, err
	}

	return map[string]interface{}{
		"info":           info,
		"devices":        devices,
		"rate":           rate,
		"settlementRate": settlementRate,
	}, nil
}

// MerchantSettleInfoUpdate 修改商户结算信息
func (m *Merchant) MerchantSettleInfoUpdate() (map[string]interface{}, error) {
	//取出用户全部信息
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	if merchant.MerchantShopTypeID == 1 && m.SettleAccountType != 1 {
		return nil, errors.New("小微企业，只能选择法人对私")
	}

	if m.SettleAccountType == 2 && len(m.SettleName) == 0 {
		return nil, errors.New("请输入结算户名")
	}

	var settleName string
	if m.SettleAccountType == 1 {
		//法人对私结算：与法人姓名一致；
		settleName = merchant.LegalPersonName
	} else if m.SettleAccountType == 2 {
		//非法人对私结算：与非法人身份证信息一致；
		settleName = m.SettleName
	} else {
		//法人对公结算：与营业执照注册名称一致
		settleName = merchant.LicenseName
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardFrontName) == 0 {
		return nil, errors.New("身份证正面照不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardBackName) == 0 {
		return nil, errors.New("身份证背面照不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleAuthName) == 0 {
		return nil, errors.New("结算授权书图片不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardNo) == 0 {
		return nil, errors.New("结算人身份证号不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardStartDate) == 0 {
		return nil, errors.New("结算人身份证有效期起始日期不能为空")
	}

	//非法人对私必填
	if m.SettleAccountType == 2 && len(m.SettleIdcardEndDate) == 0 {
		return nil, errors.New("结算人身份证有效期结束日期不能为空")
	}

	//获取结算银行信息
	bank := models.GetBankCodeById(m.SettleSubbranchCode)

	result, err := channel.LianSettleUpdate(&channel.LianUpdateParam{
		MerchantId: merchant.LDMerchantId,
		IncomeSettleInfoDTO: channel.IncomeSettleInfoDTO{
			AccountType:            cast.ToString(m.SettleAccountType),
			SettleBankcardFrontPic: m.SettleBankcardFrontPic,
			SettleName:             settleName,
			SettleBankcardNo:       m.SettleBankcardNo,
			SettleBankMobile:       m.SettleBankMobile,
			SettleBankName:         bank.BaseName,
			SettleSubbranch:        bank.Name,
			SettleSubbranchCode:    bank.BankCode,
			SettleCityName:         bank.CityName,
			SettleProvinceName:     bank.ProvinceName,
			SettleIdcardFrontPic:   m.SettleIdcardFrontName,
			SettleIdcardBackPic:    m.SettleIdcardBackName,
			SettleAuthPic:          m.SettleAuthName,
			SettleIdcardNo:         m.SettleIdcardNo,
			SettleIdcardStartDate:  m.SettleIdcardStartDate,
			SettleIdcardEndDate:    m.SettleIdcardEndDate,
		},
	})
	if err != nil {
		return nil, err
	}

	var mapd = make(map[string]interface{})
	mapd["settle_account_type"] = m.SettleAccountType
	mapd["settle_bank_card_photo"] = m.SettleBankcardFrontPic
	mapd["settle_name"] = settleName
	mapd["settle_bankcard_no"] = m.SettleBankcardNo
	mapd["settle_bank_phone"] = m.SettleBankMobile
	mapd["ld_settle_subbranch_code"] = m.SettleSubbranchCode
	if len(m.SettleIdcardFrontName) != 0 {
		mapd["settle_idcard_front_name"] = m.SettleIdcardFrontName
	}
	if len(m.SettleIdcardBackName) != 0 {
		mapd["settle_idcard_back_name"] = m.SettleIdcardBackName
	}
	if len(m.SettleAuthName) != 0 {
		mapd["settle_auth_name"] = m.SettleAuthName
	}
	if len(m.SettleIdcardNo) != 0 {
		mapd["settle_idcard_no"] = m.SettleIdcardNo
	}
	if len(m.SettleIdcardStartDate) != 0 {
		mapd["settle_idcard_start_date"] = m.SettleIdcardStartDate
	}
	if len(m.SettleIdcardEndDate) != 0 {
		mapd["settle_idcard_end_date"] = m.SettleIdcardEndDate
	}
	err = models.MerchantInfoUpdate(mapd, m.Id)
	if err != nil {
		return nil, err
	}

	return result, err
}

// MerchantShopNameUpdate 商户简称信息修改
func (m *Merchant) MerchantShopNameUpdate() (map[string]interface{}, error) {
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	result, err := channel.LianShopNameUpdate(merchant.LDMerchantId, m.MerchantName)
	if err != nil {
		return nil, err
	}

	var mapd = make(map[string]interface{})
	mapd["merchant_name"] = m.MerchantName

	err = models.MerchantInfoUpdate(mapd, m.Id)
	if err != nil {
		return nil, err
	}

	return result, nil
}

// MerchantRateRange 商户费率范围查询
func (m *Merchant) MerchantRateRange() (map[string]interface{}, error) {
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	result, err := channel.LianMerchantRateRange(merchant.LDMerchantId)
	if err != nil {
		return nil, err
	}

	for _, merchantFeeRate := range cast.ToStringSlice(result["merchantFeeRateList"]) {
		merchantFeeRateMap := cast.ToStringMap(merchantFeeRate)

		merchantInstallmentRateList := cast.ToStringSlice(merchantFeeRateMap["merchantInstallmentRateList"])
		merchantInstallmentRateJson, _ := json.Marshal(merchantInstallmentRateList)

		instalmentFeeRateList := cast.ToStringSlice(merchantFeeRateMap["instalmentFeeRateList"])
		instalmentFeeRateListJson, _ := json.Marshal(instalmentFeeRateList)

		err = models.LianMerchantRateAdd(&models.LianMerchantRate{
			MerchantId:                  m.Id,
			LDMerchantId:                merchant.LDMerchantId,
			TransType:                   cast.ToInt(merchantFeeRateMap["transType"]),
			MerchantMaxD1Rate:           cast.ToFloat32(merchantFeeRateMap["merchantMaxD1Rate"]),
			MerchantMinD1Rate:           cast.ToFloat32(merchantFeeRateMap["merchantMinD1Rate"]),
			PosFeeLimitMax:              cast.ToFloat32(merchantFeeRateMap["posFeeLimitMax"]),
			PosFeeLimitMin:              cast.ToFloat32(merchantFeeRateMap["posFeeLimitMin"]),
			MerchantInstallmentRateList: cast.ToString(merchantInstallmentRateJson),
			BankNm:                      cast.ToString(merchantFeeRateMap["bankNm"]),
			InstalmentFeeRateList:       cast.ToString(instalmentFeeRateListJson),
			InstallmentNm:               cast.ToString(merchantFeeRateMap["installmentNm"]),
			InstallmentRateMax:          cast.ToFloat32(merchantFeeRateMap["installmentRateMax"]),
			InstallmentRateMin:          cast.ToFloat32(merchantFeeRateMap["installmentRateMin"]),
		})
		if err != nil {
			return nil, err
		}
	}

	return result, nil
}

// MerchantAuditQuery 商户审核结果查询
func (m *Merchant) MerchantAuditQuery() (map[string]interface{}, error) {
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	result, err := channel.LianMerchantAuditQuery(&channel.LianMerchantAuditQueryParam{
		OutMerchantId: cast.ToString(merchant.ID),
		MerchantId:    merchant.LDMerchantId,
		AuditType:     cast.ToString(m.AuditType),
	})
	if err != nil {
		return nil, err
	}

	return result, nil
}

// MerchantGetWechatApprove 微信认证查询
func (m *Merchant) MerchantGetWechatApprove() (map[string]interface{}, error) {
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	result, err := channel.LianWechatApprove(merchant.LDMerchantId)
	if err != nil {
		return nil, err
	}

	models.LianMerchantAuthInfoAdd(&models.LianMerchantAuthInfo{
		MerchantId:       cast.ToInt(merchant.ID),
		LDMerchantId:     merchant.LDMerchantId,
		WechatMerchantId: cast.ToString(result["wechatMerchantId"]),
		ApplyStatus:      cast.ToInt(result["applyStatus"]),
		QrcodeData:       cast.ToString(result["qrcodeData"]),
		RejectReason:     cast.ToString(result["rejectReason"]),
	})

	return result, nil
}

// MerchantGetWechatAuth 微信授权状态查询
func (m *Merchant) MerchantGetWechatAuth() (map[string]interface{}, error) {
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	result, err := channel.LianWechatAuth(merchant.LDMerchantId)
	if err != nil {
		return nil, err
	}

	models.LianMerchantAuthInfoAdd(&models.LianMerchantAuthInfo{
		MerchantId:       cast.ToInt(merchant.ID),
		LDMerchantId:     merchant.LDMerchantId,
		WechatMerchantId: cast.ToString(result["wechatMerchantId"]),
		AuthState:        cast.ToInt(result["authState"]),
	})

	return result, nil
}

// MerchantGetAlipayApprove 支付宝认证查询
func (m *Merchant) MerchantGetAlipayApprove() (map[string]interface{}, error) {
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	result, err := channel.LianAlipayApprove(merchant.LDMerchantId)
	if err != nil {
		return nil, err
	}

	models.LianMerchantAuthInfoAdd(&models.LianMerchantAuthInfo{
		MerchantId:       cast.ToInt(merchant.ID),
		LDMerchantId:     merchant.LDMerchantId,
		AlipayMerchantId: cast.ToString(result["alipayMerchantId"]),
		ApplyStatus:      cast.ToInt(result["applyStatus"]),
		QrcodeData:       cast.ToString(result["qrcodeData"]),
		RejectReason:     cast.ToString(result["rejectReason"]),
	})

	return result, nil
}

// MerchantGetAlipayAuth 支付宝授权状态查询
func (m *Merchant) MerchantGetAlipayAuth() (map[string]interface{}, error) {
	merchant, err := models.MerchantByID(m.MerchantId)
	if err != nil {
		return nil, err
	}

	result, err := channel.LianAlipayAuth(merchant.LDMerchantId)
	if err != nil {
		return nil, err
	}

	models.LianMerchantAuthInfoAdd(&models.LianMerchantAuthInfo{
		MerchantId:       cast.ToInt(merchant.ID),
		LDMerchantId:     merchant.LDMerchantId,
		AlipayMerchantId: cast.ToString(result["alipayMerchantId"]),
		AuthState:        cast.ToInt(result["authState"]),
	})

	return result, nil
}

// LianMccList 获取mcc
func (m *Merchant) LianMccList() interface{} {
	return models.LianMccList()
}

// LianCodeList 联动获取省市区列表
func (m *Merchant) LianCodeList() interface{} {
	return models.LianCodeList()
}

// LianBankList 获取银行列表
func (m *Merchant) LianBankList() interface{} {
	return models.LianBankCodeListByBaseName(m.BankName, m.BankCity)
}

func channelToLian(merchant *models.Merchant) (map[string]interface{}, error) {
	//获取城市id
	code := models.GetLianCode(merchant.MerchantAddressId)
	//获取图片id
	pic := models.GetLianMerchantPicId(merchant.ID)
	//获取结算银行信息
	bank := models.GetBankCodeById(merchant.LdSettleSubbranchCode)

	var ShopMerchantId string
	if merchant.MainMerchantId == 0 {
		ShopMerchantId = ""
	} else {
		ShopMerchantId = cast.ToString(merchant.MainMerchantId)
	}

	//联动商户入驻
	data, err := channel.LianIncome(&channel.LianIncomeParam{
		OutMerchantId: cast.ToString(merchant.ID),
		IncomeMerchantInfoDTO: channel.IncomeMerchantInfoDTO{
			Account:        merchant.MerchantMobile,
			ShopType:       cast.ToString(merchant.MerchantShopTypeID),
			MerchantType:   cast.ToString(merchant.MerchantTypeID),
			ShopMerchantId: ShopMerchantId,
		},
		IncomeShopInfoDTO: channel.IncomeShopInfoDTO{
			ShopName:        merchant.MerchantName,
			MccCode:         cast.ToString(merchant.MerchantRangeCode),
			ProvinceCode:    code.ProvinceCode,
			CityCode:        code.CityCode,
			AreaCode:        code.AreaCode,
			Address:         merchant.MerchantAddress,
			DoorPic:         pic["doorPic"],
			CashierPic:      pic["cashierPic"],
			ShopPic:         pic["shopPic"],
			RelationCertPic: pic["relationCertPic"],
		},
		IncomeLegalPersonInfoDTO: channel.IncomeLegalPersonInfoDTO{
			IdcardFrontPic:  pic["idcardFrontPic"],
			IdcardBackPic:   pic["idcardBackPic"],
			IdcardHoldPic:   pic["idcardHoldPic"],
			IdcardName:      merchant.LegalPersonName,
			IdcardNo:        merchant.LegalPersonIdcard,
			IdcardStartDate: merchant.LegalPersonIdcardValidityBegin,
			IdcardEndDate:   merchant.LegalPersonIdcardValidityEnd,
			ContactType:     merchant.LegalContactType,
			ContactName:     merchant.LegalContactName,
			ContactIdcardNo: merchant.LegalContactIdCardNo,
			ContactMobile:   merchant.LegalContactMobile,
		},
		IncomeLicenseInfoDTO: channel.IncomeLicenseInfoDTO{
			LicensePic:       pic["licensePic"],
			LicenseName:      merchant.LicenseName,
			LicenseCode:      merchant.LicenseCode,
			LicenseStartDate: merchant.LicenseStartDate,
			LicenseEndDate:   merchant.LicenseEndDate,
			LicenseAddress:   merchant.LicenseAddress,
		},
		IncomeSettleInfoDTO: channel.IncomeSettleInfoDTO{
			AccountType:            cast.ToString(merchant.SettleAccountType),
			SettleBankcardFrontPic: pic["settleBankcardFrontPic"],
			SettleName:             merchant.SettleName,
			SettleBankcardNo:       merchant.SettleBankcardNo,
			SettleBankMobile:       merchant.SettleBankPhone,
			SettleBankName:         bank.BaseName,
			SettleSubbranch:        bank.Name,
			SettleSubbranchCode:    bank.BankCode,
			SettleCityName:         bank.CityName,
			SettleProvinceName:     bank.ProvinceName,
			SettleIdcardFrontPic:   pic["settleIdcardFrontPic"],
			SettleIdcardBackPic:    pic["settleIdcardBackPic"],
			SettleAuthPic:          pic["settleAuthPic"],
			SettleIdcardNo:         merchant.SettleIdcardNo,
			SettleIdcardStartDate:  merchant.SettleIdcardStartDate,
			SettleIdcardEndDate:    merchant.SettleIdcardEndDate,
		},
	})
	if err != nil {
		return nil, err
	}
	return data, nil
}
